<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="static/dayjs.min.js"></script>
    <script src="static/plugin/utc.min.js"></script>
    <script src="static/plugin/timezone.min.js"></script>

    <title>日志监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.8;
            font-size: 1.1em;
        }

        .content {
            padding: 30px;
        }

        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .status-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #007bff;
            transition: transform 0.3s ease;
        }

        .status-card:hover {
            transform: translateY(-5px);
        }

        .status-card h3 {
            color: #495057;
            margin-bottom: 10px;
            font-size: 1.2em;
        }

        .status-value {
            font-size: 2em;
            font-weight: bold;
            color: #007bff;
        }

        .status-badge {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: bold;
        }

        .status-connected {
            background: #d4edda;
            color: #155724;
        }

        .status-disconnected {
            background: #f8d7da;
            color: #721c24;
        }

        .controls {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1em;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
        }

        .logs-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }
        .log-detail-modal{
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 80vw;
            margin: 20px auto;
            max-height: 80vh;
            overflow-y: scroll;
        }

        .logs-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .logs-table th,
        .logs-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        .logs-table th {
            background: #495057;
            color: white;
            font-weight: 600;
        }

        .logs-table tr:hover {
            background: #f8f9fa;
        }

        .log-message {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .log-timestamp {
            font-family: monospace;
            color: #6c757d;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .chart-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .chart-title {
            font-size: 1.3em;
            margin-bottom: 15px;
            color: #495057;
        }

        .hourly-chart {
            height: 200px;
            display: flex;
            align-items: end;
            gap: 2px;
            padding: 20px 0;
        }

        .chart-bar-parent {
            flex: 1;
            position: relative;
            display: flex;
            align-items: flex-end;
        }
        .chart-bar-parent:hover{
            background: #d0d6dc;
        }

        .chart-bar {
            flex: 1;
            background: #007bff;
            border-radius: 3px 3px 0 0;
            /* min-height: 5px; */
            position: relative;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .chart-bar:hover {
            background: #0056b3;
        }

        .chart-label {
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 0.8em;
            color: #6c757d;
            white-space: nowrap;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 2em;
            }
            
            .status-grid {
                grid-template-columns: 1fr;
            }
            
            .controls {
                flex-direction: column;
            }
            
            .logs-table {
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 日志监控系统</h1>
            <p>实时监控 Elasticsearch 错误日志</p>
        </div>

        <div class="content">
            <!-- 状态概览 -->
            <div class="status-grid">
                <div class="status-card">
                    <h3>ES 连接状态</h3>
                    <div id="es-status" class="status-badge status-disconnected">检查中...</div>
                </div>
                <div class="status-card">
                    <h3>24小时错误总数</h3>
                    <div id="total-errors" class="status-value">-</div>
                </div>
                <div class="status-card">
                    <h3>最后检查时间</h3>
                    <div id="last-check" class="status-value" style="font-size: 1.2em;">-</div>
                </div>
            </div>

            <!-- 控制按钮 -->
            <div class="controls">
                <button class="btn btn-primary" onclick="refreshStatus()">🔄 刷新状态</button>
            </div>

            <!-- 24小时错误趋势图 -->
            <div class="chart-container">
                <div class="chart-title">📈 24小时错误趋势</div>
                <div id="hourly-chart" class="hourly-chart">
                    <div class="loading">加载中...</div>
                </div>
            </div>

             <!-- 控制按钮 -->
             <div class="controls">
                <button class="btn btn-secondary" onclick="loadLogs(1)">📋 最近1小时</button>
                <button class="btn btn-secondary" onclick="loadLogs(6)">📋 最近6小时</button>
                <button class="btn btn-secondary" onclick="loadLogs(24)">📋 最近24小时</button>
            </div>

            <!-- 日志列表 -->
            <div class="logs-section">
                <div class="chart-title">📝 错误日志详情</div>
                <div id="logs-container">
                    <div class="loading">点击上方按钮加载日志...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        if(window.dayjs_plugin_utc){
            dayjs.extend(window.dayjs_plugin_utc)
        }else{
            console.log('utc not found');
        }
        if(window.dayjs_plugin_timezone){
            dayjs.extend(window.dayjs_plugin_timezone)
        }else{
            console.log('timezone not found');
        }

        // 统一的401错误处理函数
        function handleUnauthorized(response) {
            if (response.status === 401) {
                console.log('登录已过期，跳转到登录页面');
                window.location.href = '/login';
                return true; // 表示已处理
            }
            return false; // 表示未处理
        }

        // 统一的API请求函数
        async function apiRequest(url, options = {}) {
            try {
                const response = await fetch(url, {
                    ...options,
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        ...options.headers
                    }
                });

                // 检查401错误
                if (handleUnauthorized(response)) {
                    window.location.href = './login';
                    return null;
                }

                return response;
            } catch (error) {
                console.error('API请求失败:', error);
                return null;
            }
        }

        // 页面加载时自动刷新状态
        document.addEventListener('DOMContentLoaded', function() {
            refreshStatus();
        });

        // 刷新状态
        async function refreshStatus() {
            try {
                const response = await apiRequest('/es-monitor/api/status');
                if (!response) return; // 401已处理

                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }

                // 更新ES状态
                const esStatusEl = document.getElementById('es-status');
                esStatusEl.textContent = data.es_status === 'connected' ? '已连接' : '未连接';
                esStatusEl.className = `status-badge ${data.es_status === 'connected' ? 'status-connected' : 'status-disconnected'}`;

                // 更新错误总数
                document.getElementById('total-errors').textContent = data.total_errors_24h;

                // 更新最后检查时间
                document.getElementById('last-check').textContent = data.last_check;

                // 更新趋势图
                updateHourlyChart(data.hourly_stats);

            } catch (error) {
                console.error('获取状态失败:', error);
                document.getElementById('es-status').textContent = '连接失败';
                document.getElementById('es-status').className = 'status-badge status-disconnected';
            }
        }

        // 更新小时趋势图
        function updateHourlyChart(hourlyStats) {
            const chartContainer = document.getElementById('hourly-chart');
            chartContainer.innerHTML = '';

            const hours = Object.keys(hourlyStats).sort();
            const maxValue = Math.max(...Object.values(hourlyStats));

            hours.forEach(hour => {
                const value = hourlyStats[hour]; 
                //柱子高度最小为5%，以便方便现实
                const height = maxValue > 0 ? (value / maxValue) * 100 : 0;
                
                const barParent = document.createElement('div');
                barParent.className = 'chart-bar-parent';
                barParent.style.height = `100%`;

                
                const bar = document.createElement('div');
                bar.className = 'chart-bar';
                bar.style.height = `${height}%`;

                barParent.title = `${hour}: ${value} 个错误`;
                bar.setAttribute('data-start', hour);

                const label = document.createElement('div');
                label.className = 'chart-label';
                label.textContent = hour.split(' ')[1]; // 只显示小时部分
                bar.onclick = function() {
                    const start = this.getAttribute('data-start');
                    loadLogs(0, start);
                }
                bar.appendChild(label);
                barParent.appendChild(bar);
                chartContainer.appendChild(barParent);
            });
        }

        function formatTimestamp(ts) {
            if (!ts) return '';
            //时区转换，utc转换为本地时间 2025-06-23T10:51:52.030Z
            return dayjs(ts).tz("Asia/Shanghai").format('YYYY-MM-DD HH:mm:ss');
        }

        function formatPath(path) {
            if (!path) return '';
            return path.split('/').pop().split('.')[0];
        }

        // 加载日志
        async function loadLogs(hours, start, pageIndex=1) {
            const container = document.getElementById('logs-container');
            container.innerHTML = '<div class="loading">加载中...</div>';
            
            try {
                const response = await apiRequest(`/es-monitor/api/logs?hours=${hours}&limit=100&start=${start || ''}&pageIndex=${pageIndex}`);
                if (!response) return; // 401已处理

                const data = await response.json();

                if (data.error) {
                    throw new Error(data.error);
                }

                if (data.logs.length === 0) {
                    container.innerHTML = '<div class="loading">暂无错误日志</div>';
                    return;
                }

                window.logs = data.logs;

                // 创建表格
                let tableHtml = `
                    <table class="logs-table">
                        <thead>
                            <tr>
                                <th>时间戳</th>
                                <th>服务</th>
                                <th>日志级别</th>
                                <th>消息内容</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                

                data.logs.forEach((log, index) => {
                    const message = log.message.length > 100 ? 
                        log.message.substring(0, 100) + '...' : log.message;
                    
                    tableHtml += `
                        <tr>
                            <td class="log-timestamp">${formatTimestamp(log.timestamp)}</td>
                            <td><span class="status-badge status-disconnected">${formatPath(log.source.log.file.path)}</span></td>
                            <td><span class="status-badge status-disconnected">${log.level}</span></td>
                            <td class="log-message" title="${log.message}">${message}</td>
                            <td>
                                <button class="btn btn-secondary" onclick="showLogDetail(${index})">
                                    查看详情
                                </button>
                            </td>
                        </tr>
                    `;
                });

                tableHtml += `
                        </tbody>
                    </table>
                    <p style="margin-top: 10px; color: #6c757d;">
                        显示 ${data.logs.length} 条日志 (共 ${data.total} 条)
                    </p>
                `;
                tableHtml += `<div class="pagination">`;
                const totalPages = Math.ceil(data.total / 100);

                //分页，如果pageIndex为1，则不显示上一页
                if (pageIndex > 1) {
                    tableHtml += `
                        <button class="btn btn-secondary" onclick="loadLogs(${hours}, '${start}', ${pageIndex - 1})">上一页</button>
                    `;
                }
                if (pageIndex < totalPages) {
                    tableHtml += `
                        <button class="btn btn-secondary" onclick="loadLogs(${hours}, '${start}', ${pageIndex + 1})">下一页</button>`
                }
                tableHtml += `
                    </div>
                `;

                container.innerHTML = tableHtml;

            } catch (error) {
                console.error('加载日志失败:', error);
                container.innerHTML = `<div class="error">加载日志失败: ${error.message}</div>`;
            }
        }

        // 显示日志详情
        function showLogDetail(idx) {
            const log = window.logs[idx];
            const detailHtml = `
                <div class="log-detail-modal" style="background: white; padding: 20px; border-radius: 10px; margin: 20px auto;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3 style="margin:0;">日志详情</h3>
                            <span style="color:#888;">${log.timestamp}</span>
                        </div>
                        <button class="btn btn-primary" onclick="this.closest('.log-detail-modal').parentElement.remove()">关闭</button>
                    </div>
                    <p><strong>级别:</strong> ${log.level}</p>
                    <p><strong>消息:</strong></p>
                    <pre style="background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto;">${log.message}</pre>
                    <p><strong>完整日志:</strong></p>
                    <pre style="background: #f8f9fa; padding: 10px; border-radius: 5px; overflow-x: auto; max-height: 300px;">${JSON.stringify(log.source, null, 2)}</pre>
                </div>
            `;
            
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                background: rgba(0,0,0,0.5); z-index: 1000; display: flex; 
                align-items: center; justify-content: center;
            `;
            overlay.innerHTML = detailHtml;
            overlay.onclick = function(e) {
                if (e.target === overlay) overlay.remove();
            };
            document.body.appendChild(overlay);
        }

        // 自动刷新（每30秒）
        setInterval(refreshStatus, 30000);
    </script>
</body>
</html> 